<template>
  <a-form :model="value" layout="inline" class="dynamic-form">
    <form-item
      v-for="item in formConfig"
      :key="item.key"
      :item="item"
      v-bind="item"
      :name="item.key"
      :value="value[item.key]"
      @input="handleInput($event, item.key)"
      @change="handleSelect($event, item.key)"
    />
    <slot></slot>
  </a-form>
</template>

<script setup>
import { watch } from 'vue'
import dayjs from 'dayjs'
import FormItem from './FormItem'

const emit = defineEmits(['update:value', 'input'])
const props = defineProps({
  formConfig: {
    type: Array,
    required: true
  },
  value: {
    type: Object,
    required: true
  }
})
watch(
  () => props.formConfig,
  (val) => {
    if (val.length) {
      setTimeout(() => setDefaultValue(), 100)
    }
  }
)
const handleInput = (e, key) => {
  emit('update:value', { ...props.value, [key]: e.target.value })
}
const handleSelect = (select, key) => {
  emit('update:value', { ...props.value, [key]: select })
}
const setDefaultValue = () => {
  const formData = { ...props.value }
  // 设置默认值
  props.formConfig.forEach((item) => {
    const { key, value, type, defaultValue } = item
    if (formData[key] === undefined || formData[key] === null) {
      formData[key] = value
      switch (type) {
        case '长日期范围':
          formData[key] = [dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'), dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')]
          break
        case '短日期范围':
          formData[key] = getDataRange(defaultValue)
          break
        case '长日期':
          formData[key] = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
          break
        case '短日期':
          formData[key] = dayjs().format('YYYY-MM-DD')
          break
        default:
          break
      }
    }
  })
  emit('update:value', { ...formData })
}
const getDataRange = (defaultValue) => {
  switch (defaultValue) {
    case '空':
      return []
    case '当天':
      return [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    case '最近7天':
      return [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    case '最近一个月':
      return [dayjs().subtract(1, 'month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    default:
      return [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  }
}
</script>
